/*
 * Base64Util.java
 */

package xq.util;

/**
 *
 * @author ThorntonRP
 */
public class Base64Util {

	public static String encode(byte[] data) {
		StringBuilder sb = new StringBuilder(data.length * 2);
		for (int i = 0; i < data.length; i++) {
			String hex = Integer.toHexString(data[i] & 0xFF);
			if (hex.length() == 1) {
				sb.append('0');
			}
			sb.append(hex);
		}
		return sb.toString();
	}
	
	public static byte[] decode(String data) {
		if (data.length() % 2 != 0) {
			throw new IllegalArgumentException("data string must have an even number of characters");
		} else {
			byte[] result = new byte[data.length() / 2];
			for (int i = 0, j = 0; i < data.length(); i+=2,j++) {
				String hex = data.substring(i, i+2);
				result[j] = (byte) Integer.parseInt(hex, 16);
			}
			return result;
		}
	}
}
